package org.chw.netty.server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName: SocketServer
 * @Description: socket服务
 * @Autor: Vincent.Chen
 * @Create: 2018/6/11 16:29
 * @Version: 1.0
 **/
public class SocketServer {
  private static final Logger LOGGER = LoggerFactory.getLogger(SocketServer.class);
  private int port;

  public SocketServer(int port) {
    this.port = port;
  }

  public void start() {
    server();
  }

  private void server() {
    try {
      ServerSocket server = new ServerSocket(8080);
      LOGGER.info("Server listen:{} port:{}", server.getInetAddress(), server.getLocalPort());
      while(true){
        Socket socket = server.accept();
        LOGGER.info("Client connect.......{}", socket.getInetAddress());
        InputStream ips = socket.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(ips));
        LOGGER.info("Client send:{}", br.readLine());
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

  }

  private void reader(InputStream ips) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(ips));
    String str;
    StringBuilder sb = new StringBuilder();
    while ((str = br.readLine()) != null) {
      sb.append(str);
    }
    LOGGER.info("Client send:{}", sb.toString());
  }

  private void close(OutputStream ops, InputStream ips, BufferedReader br) {
    try {
      ops.flush();
      ops.close();
      ips.close();
      br.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
